package com.zhdl.websocket.conf;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.zhdl.common.ytools.PublicTools;
import com.zhdl.modules.prefiresys.service.FactoryLocalHostService;
import com.zhdl.modules.prefiresys.web.response.AllHostListResp;
import com.zhdl.modules.prefiresys.web.service.CollectService;
import com.zhdl.websocket.WebSocketRunClient;
import com.zhdl.websocket.server.WebSocketRunServer;
import com.zhdl.websocket.service.WebSocketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Configuration
public class MyWebSocketConf {

    /**
     * 在 Config 中 注入Service
     *
     * @param webSocketService 需要注入的service
     */
    @Autowired
    public void setWebSocketService(WebSocketService webSocketService) {
        WebSocketRunServer.webSocketService = webSocketService;
    }

    WebSocketRunClient WebSocketRunClient;

    public Map<String, WebSocketRunClient> maps;

    @Autowired
    private FactoryLocalHostService localHostService;

    @Bean
    public Map<String, WebSocketRunClient> WebSocketRunClientMap(){

        Map<String, WebSocketRunClient> retMap = new HashMap<>(5);

        System.out.println("----------------------------------------------------------");

        /*
            临时保证最后有一个值
         */
        String sid= "fss1";//一体机编号(目前暂定为fss1)

        List<AllHostListResp> allHostlist = localHostService.getAllHostlist();

        //从本地设备列表中拿到 该设备的 设备编号
        for (AllHostListResp allHostListResp : allHostlist) {
            AllHostListResp allHostListResp1 = new AllHostListResp();
            BeanUtil.copyProperties(allHostListResp, allHostListResp1, CopyOptions.create().setIgnoreNullValue(true));
            sid = allHostListResp1.getHostNo();
        }

        /*
            websocket 连接路径
         */
        String websocketUrl= PublicTools.getString("application","websocketUrl") + "/" + "client_" + sid;
        /*
            websocket 连接名称
         */
        String websocketName=PublicTools.getString("application","websocketName");;

        /*
            启用心跳判断
         */
        boolean enableReconnection = true;
        boolean enableHeartbeat = true;
        /*
            休眠时间
         */
        Integer heartbeatInterval = 20000;

        try{
            WebSocketRunClient = new WebSocketRunClient(new URI(websocketUrl),websocketName);
            WebSocketRunClient.connect();
            WebSocketRunClient.setConnectionLostTimeout(0);

            String finalSid = sid;

            new Thread(()->{
                while (true){
                    try {
                        Thread.sleep(heartbeatInterval);
                        /*
                            启动心跳
                         */
                        if(enableHeartbeat){
                            WebSocketRunClient.send("client"+"_"+ finalSid);
                        }
                    } catch (Exception e) {
                        try {
                            /*
                                连接失败，重新启动心跳
                             */
                            if(enableReconnection){
                                WebSocketRunClient.reconnect();
                                WebSocketRunClient.setConnectionLostTimeout(0);
                            }

                        }catch (Exception ex){
                            log.error("[websocket {}] 重连异常,{}",websocketName,ex.getMessage());
                        }
                    }
                }
            }).start();
            retMap.put(websocketName,WebSocketRunClient);
            this.maps = retMap;
        } catch (URISyntaxException ex) {
            log.error("[websocket {}] 连接异常,{}",websocketName,ex.getMessage());
        }
        return retMap;
    }
    @Resource
    private CollectService collectService;

    @Scheduled(fixedRate = 1000)
    public void sse(){
        String jsonStr = JSONUtil.toJsonStr(collectService.sseResp);
        WebSocketRunClient.send(jsonStr);
    }
}